﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Ccr.Core;

namespace XcoAppSpaces.Security.Basic
{
	class WorkerSessionInfo
	{
		public IPort Worker { get; private set; }
		public bool HasFullAccess { get; private set; }
		private readonly List<Type> allowedMessageTypes;

		public WorkerSessionInfo(IPort worker, List<Type> allowedMessageTypes)
		{
			this.Worker = worker;
			this.allowedMessageTypes = allowedMessageTypes;

			//check user has full access (simplifies check if message is allowed) (is the case when number of allowed message types equals the number of worker ports)
			HasFullAccess = ((worker is IPortSet && allowedMessageTypes.Count == ((IPortSet)worker).Ports.Count) || (!(worker is IPortSet) && allowedMessageTypes.Count == 1));
		}

		public bool IsAllowed(Type messageType)
		{
			if (HasFullAccess)
				return true; //all message types allowed if user has full access to worker

			//check if type is in the list of allowed types
			foreach (Type allowedType in allowedMessageTypes)
			{
				if (messageType == allowedType)
					return true;
			}
			//if not, additionally check if type is assignable to any of the types in the allowed list
			foreach (Type allowedType in allowedMessageTypes)
			{
				if (allowedType.IsAssignableFrom(messageType))
					return true;
			}
			//if not, return false because posting this message is not allowed in this session
			return false;
		}
	}
}
